var shopDAO = require('../models/shopDAO')

var shopController = {
    //查询购物车信息
    getShopList: function (req, res) {
        var userId = req.params.uId
        shopDAO.getShopList(userId, function (err, results) {
            if (err) {
                res.json({ code: 500,data:-1, msg: '购物车查询失败' })
            } else {
               
                res.json({ code: 200, data: results, msg: 'ok' })
            }
        })
    },
    //增加商品进购物车
    addProduct: function (req, res) {
        var productId= req.body.productId
        var userId=req.params.uId
        var shop = { productId, userId}
        shopDAO.getProductId(productId,function(err,results){
            if(err){
                res.json({ code: 500, msg: '购物车查询失败' })
            }else {
                if(results.length==0){
                    shopDAO.addProduct(shop, function (err, results) {
                        if (err) {
                            res.json({ code: 500,data:-1, msg: '加入购物车失败' })
                        } else {
                            if (results.affectedRows == 0) {
                                res.json({ code: 200,data:-1, msg: '加入购物车失败' })
                            } else {
                                res.json({ code: 200, data: results, msg: '成功加入购物车' })
                            }
                        }
                    })
                }else{
                    res.json({ code: 200,data:-1, msg: '该商品已经加入购物车啦!' }) 
                }  
            }
        })
       
    },
    //删除购物车
    delProduct: function (req, res) {
        var shopIds = (req.params.shopIds).split(',')
        shopIds.push(0)
        console.log(shopIds)
        shopDAO.delProduct(shopIds, function (err, results) {
            if (err) {
                res.json({ cede: 500,data:-1, msg: "删除失败" })
            } else {
                if (results.affectedRows == 0) {
                    res.json({ cede: 200,data:-1, msg: "删除失败" })
                } else {
                    res.json({ code: 200, data: results, msg: "删除成功" })
                }
            }
        })
    },
    //更新购物车
    updateProductNum: function (req, res) {
        var shop = { count: req.params.count, shopId: req.params.shopId}
        console.log(shop)
        shopDAO.updateProductNum(shop, function (err, results) {
            if (err) {
                res.json({ code: 500,data:-1, msg: '数据库错误，更新失败'})
            } else {
                if (results.affectedRows == 0) {
                    res.json({ cede: 200,data:-1, msg: "没有这条数据，更新失败" })
                } else {
                    res.json({ code: 200, data: results, msg: "更新成功" })
                }
            }
        })
    }
}
module.exports = shopController
